<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>添加员工</title>
    </head>
    <body>
        <h3>添加员工</h3>
        <form action="" method="post">
            <table width="70%" >
                <tr><td >姓名：<input id="name" type="text" name="name" /></td></tr>
                <tr><td >手机号：<input id="phone" type="text" name="phone" /></td></tr>
                <tr><td id="departments">所属部门：</td></tr>
                <tr><td ><input id="btn" type="button" value="添加"/></td></tr>
            </table>
        </form>

        <script src="js/axios-0.18.0.js"></script>
        <script>
            //1. 当页面加载完成后，发送ajax请求
            window.onload = function () {
                //2. 发送ajax请求
                axios({
                    method:"get",
                    url:"http://localhost/getAllDepartments"
                }).then(function (resp) {
                    let list = resp.data;
                    let departmentData="所属部门：";
                    for (let i = 0; i < list.length ; i++) {
                        let obj = list[i];
        //<input type="radio" name="departmentId" value="${department.id}" >${department.name}
                        departmentData += "<input type=\"radio\" name=\"departmentId\" value="+
                        obj.id +" >"+obj.name;
                    }
                    // 设置表格数据
                    document.getElementById("departments").innerHTML = departmentData;
                })
            }
            //1. 给按钮绑定单击事件
            document.getElementById("btn").onclick = function () {
                // 将表单数据转为json
                var formData = {
                    name:"",
                    phone:"",
                    departmentId:"",
                };
                // 获取表单数据
                let name = document.getElementById("name").value;
                // 设置数据
                formData.name = name;

                // 获取表单数据
                let phone = document.getElementById("phone").value;
                // 设置数据
                formData.phone = phone;

                let departmentId = document.getElementsByName("departmentId");
                for (let i = 0; i < departmentId.length; i++) {
                    if(departmentId[i].checked){
                        //
                        formData.departmentId = departmentId[i].value ;
                    }
                }
                console.log(formData);
                //2. 发送ajax请求
                axios({
                    method:"post",
                    url:"http://localhost/addEmployee",
                    data:formData
                }).then(function (resp) {
                    // 判断响应数据是否为 success
                    if(resp.data == "success"){
                        location.href = "employee_list.html";
                    }
                })
            }
        </script>
    </body>
</html>